package linter.linterjava.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import linter.linterjava.POJO.DO.Article;
import linter.linterjava.POJO.DTO.ArticleDTO;
import linter.linterjava.POJO.UtilDTO.PageInfoDTO;
import linter.linterjava.mapper.ArticleMapper;
import linter.linterjava.service.ArticleService;
import linter.linterjava.utils.UploadFileUtil;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import static linter.linterjava.custom.Constant.DEFAULT_IMG_URL_NOTE;
import static linter.linterjava.custom.CustomResultType.*;

/**
 * @author 北煜
 */
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    @Resource
    ArticleMapper articleMapper;

    @Override
    @CacheEvict(value = "articles", key = "#uuid + ':*'")
    public String createArticle(ArticleDTO articleDTO, Long uuid) {
        Article article = buildArticleFromDTO(articleDTO, uuid, true);
        int flag = articleMapper.insert(article);
        return flag != 1 ? CREATION_ERROR : CREATION_SUCCESS;
    }

    @Override
    @CacheEvict(value = "articles", key = "#uuid + ':*'")
    public String updateArticle(ArticleDTO articleDTO, Long uuid) {
        System.out.println(articleDTO);
        Long articleUserId = articleMapper.selById(articleDTO.getId());
        if (!articleUserId.equals(uuid)) {
            return DELETE_NOT_PRIVILEGE;
        }
        Article article = buildArticleFromDTO(articleDTO, uuid, false);
        int flag = articleMapper.update(article, new QueryWrapper<Article>()
                .eq("user_id", uuid).eq("id", articleDTO.getId()).eq("is_delete", 0));
        return flag != 1 ? UPDATE_ERROR : UPDATE_SUCCESS;
    }

    @Override
    @CacheEvict(value = "articles", key = "#uuid + ':*'")
    public PageInfo<Article> getArticle(PageInfoDTO pageInfoDTO, Long uuid) {
        int pageSize = Optional.ofNullable(pageInfoDTO.getPageSize()).orElse(10);
        int pageNum = Optional.ofNullable(pageInfoDTO.getPageNum()).orElse(1);
        PageHelper.startPage(pageNum, pageSize);
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        switch (pageInfoDTO.getType()) {
            case "hot":
                queryWrapper.orderByDesc("view_nub");
                break;
            case "recommend":
                queryWrapper.eq("is_delete", 0);
                break;
            default:
                queryWrapper.eq("user_id", uuid).eq("is_delete", 0);
                break;
        }
        return new PageInfo<>(articleMapper.selectList(queryWrapper));
    }

    // TODO:这里似乎并没有进行过缓存更新
    @Override
    @Cacheable(value = "article", key = "#articleDTO.id != null ? #articleDTO.id : #articleDTO.articleName != null ? #articleDTO.articleName : #articleDTO.articleIntro != null ? #articleDTO.articleIntro : #articleDTO.articleContent")
    public List<Article> queryArticle(ArticleDTO articleDTO, Long uuid) {
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        if (articleDTO.getArticleName() != null && !articleDTO.getArticleName().isEmpty()) {
            queryWrapper.like("article_name", "%" + articleDTO.getArticleName() + "%").eq("is_delete", 0);
        } else if (articleDTO.getArticleIntro() != null && !articleDTO.getArticleIntro().isEmpty()) {
            queryWrapper.like("article_intro", "%" + articleDTO.getArticleIntro() + "%").eq("is_delete", 0);
        } else if (articleDTO.getArticleContent() != null && !articleDTO.getArticleContent().isEmpty()) {
            queryWrapper.like("article_content", "%" + articleDTO.getArticleContent() + "%").eq("is_delete", 0);
        }
        return articleMapper.selectList(queryWrapper);
    }

    @Override
    public Article getArticleById(Long articleId, Long uuid) {
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", articleId).eq("is_delete", 0);
        return articleMapper.selectOne(queryWrapper);
    }

    @Override
    @CacheEvict(value = "article", key = "#articleId")
    public String delArticle(Long articleId, Long uuid) {
        Long articleUserId = articleMapper.selById(articleId);
        if (!articleUserId.equals(uuid)) {
            return DELETE_NOT_PRIVILEGE;
        }
        Boolean isDel = articleMapper.isDel(articleId);
        if (!isDel) {
            QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", articleId);
            Article article = new Article();
            article.setIsDelete(1);
            int flag = articleMapper.update(article, queryWrapper);
            return flag > 0 ? DELETE_SUCCESS : DELETE_ERROR;
        }
        return THIS_DATA_DELETED;
    }

    private Article buildArticleFromDTO(ArticleDTO articleDTO, Long uuid, boolean isNew) {
        Article article = new Article();
        Date date = new Date();
        article.setUserId(uuid);
        article.setArticleName(articleDTO.getArticleName());
        article.setArticleIntro(articleDTO.getArticleIntro());
        article.setArticleContent(articleDTO.getArticleContent());
        if (isNew) {
            article.setLikeNub(0);
            article.setCollectNub(0);
            article.setReviewNub(0);
            article.setViewNub(0);
            article.setCreateTime(date);
        }
        article.setUpdataTime(date);
        MultipartFile file = articleDTO.getFile();

        if (file != null && !file.isEmpty()) {
            String url = UploadFileUtil.uploadImageToQiniu(file, uuid, "Article");
            if (url != null) {
                article.setArticleCoverImg(url);
            }
        } else if (!isNew) {
            String oUrl = articleMapper.selectOne(new QueryWrapper<Article>()
                            .eq("id", articleDTO.getId())
                            .eq("user_id", uuid)
                            .eq("is_delete", 0))
                    .getArticleCoverImg();
            article.setArticleCoverImg(oUrl);
        } else {
            article.setArticleCoverImg(DEFAULT_IMG_URL_NOTE);
        }
        return article;
    }
}
